<template>
	<view class="booking">
		<navBar />
		<!-- 返回 -->
		<Nav title="在线预约" filtertitle="意向单查询" :inpdata="inputData" @finsh="onFinshData"  />
		<!-- <view class="titles">在线预约</view> -->
		 <!-- <text>当前滚动高度：{{ scrollTop }}px</text> -->
		<!-- 我的意向单 :style="NavHeight"-->
		<scroll-view class="mybook" scroll-y="true">
			<view class="bkitem" v-for="(item,index) in bookingList" :key="index">
				<view class="bkrol">
					意向单流水号：<text class="sheetc">{{ item.sheetCode }}</text>
				</view>
				<view class="bkrol" v-if="item.customerName">
					<text>客户名称：<text class="colorb names">{{ item.customerName }}</text></text>
				</view>
				<view class="bkrol" v-if="item.cusEntryName">
					<text>客户所填名称：<text class="colorb names">{{ item.cusEntryName }}</text></text>
				</view>
				<view class="bkrol bkdjs">
					<text class="colors">联系人：<text class="colorb">{{ item.contactMan }}</text></text>
					<text class="colors">电话号：<text class="colorb">{{ item.phone }}</text></text>
					
				</view>
				<view class="disw">
					<text class="bkrol colors">业务类型编码：<text class="status" v-if="item.businessType">{{ item.businessType }}</text></text>
					<text class="bkrol colors">客户业务类型：<text class="status" v-if="item.customerBusiness">{{ item.customerBusiness }}</text></text>
				</view>
				<uni-collapse ref="collapse">
					<uni-collapse-item title="意向单详情：" >
						<view>
							<view class="bkrol">邮寄单号：<text class="sheetc">{{ item.email }}</text></view>
							<view class="bkrol bkdjs">
								<text class="colors">样品信息：<text class="colorb">{{ item.sampleInfo }}</text></text>
								<text class="colors">样品类型：<text class="colorb">{{ item.sampleType }}</text></text>
							</view>
							<view class="bkrol colors">
								附件：
							</view>
							<view class="bkdjs pd10" v-for="(atts,indexs) in item.attach" :key="indexs">
								<text >{{ atts.attName }}</text>
								<view class="controls">
									<text class="rolsl" @click="Preview(atts.attURL)">预览</text>
									<text @click="Download(atts.attURL,atts.attName)">下载</text>
								</view>
							</view>
							<view class="remark"><text class="colors">备注：</text>{{ item.remark }}</view>
						</view>
					</uni-collapse-item>
				</uni-collapse>
			</view>
		</scroll-view>
		<view class="toolbar-height"></view>
		<view class="toolbars">
			<view class="button-grounp">
				<!-- 添加 -->
				<view class="button payment-button" @tap="onAddBooking()">
					<uni-icons type="plus-filled" class="icons" color="#fff" size="15"></uni-icons>
					添加
				</view>
			</view>
		</view>
		<!-- 弹窗 -->
		<uni-popup ref="bookingModal" type="dialog">
			<uni-popup-dialog  title="新增意向单" :before-close="true" type="info" @confirm="onConfirmBookingModal" @close="onBookingClose">
				<view class="form-wrap modal">
					<view class="form-item">
						<view class="label">样品类型</view>
						<view class="form-control">
							<input v-model="SampleType" placeholder="请输入样品类型" />
						</view>
					</view>
					<view class="form-item">
						<view class="label">样品信息</view>
						<view class="form-control">
							<input v-model="SampleInfo" placeholder="请输入样品信息" />
						</view>
					</view>
					<view class="form-item">
						<view class="label">联系人</view>
						<view class="form-control">
							<input v-model="ContactMan" placeholder="请输入联系人" />
						</view>
					</view>
					<view class="form-item">
						<view class="label">电话</view>
						<view class="form-control">
							<input v-model="Phone" placeholder="请输入电话" />
						</view>
					</view>
					<view class="form-item">
						<view class="label">客户名称</view>
						<view class="form-control">
							<input v-model="CusEntryName" placeholder="请输入客户名称" />
						</view>
					</view>
					<view class="form-item">
						<view class="label">邮寄单号</view>
						<view class="form-control">
							<input v-model="EmailCode" placeholder="请输入邮寄单号" />
							
						</view>
					</view>
					<view class="form-item">
						<view class="label">备注</view>
						<view class="form-control">
							<input v-model="Remark" placeholder="请输入备注" />
						</view>
					</view>
					<view class="form-item">
						<view class="uploadfile" @click="onUploadFile">上传附件</view>
						<view class="filelist">
							<template v-if="Attachment.length > 0">
								<view class="files" v-for="(item,index) in Attachment" :key="index">
									<text class="textf">{{item.attName}}</text>
									<view class="delfiles" @click="onDelFiles(index)"></view>
								</view>
							</template>
						</view>
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	// base64
	import {
		pathToBase64
	} from "@/utils/imgtooles";
	// 引入api
	import { 
		postProgramCustomerIntention, // 意向单操作
		getProgramCustomerIntention, // 意向单查询
	} from "@/proxy/program/program.api.js";
	export default {
		data(){
			return{
				SampleType:"", // 样品类型
				SampleInfo:"", // 样品信息
				ContactMan:"", // 联系人
				Phone:"", // 电话
				EmailCode:"", // 邮寄单号
				CusEntryName:"", // 客户名称
				bookingList:[] ,// 意向单列表
				Remark:"", // 备注
				inputData:[
					{
						title: "联系人",
						placeholder:"请输入联系人",
						inpValue:"",
						key: "contactMan", //键名 接收对象名字
					}
				],
				Attachment: [], // 附件上传
			}
		},
		async mounted() {
			await this.getProgramCustomerIntentionData(); // 获取意向单
		},
		methods:{
			// 筛选后的值
			async onFinshData(data){
				await this.getProgramCustomerIntentionData(data.contactMan); // 获取意向单
			},
			// 确定添加意向单
			async onConfirmBookingModal(){
				var that = this;
				const { customerCode,businessCode,userID,userPhone } = uni.getStorageSync("userInfo");
				// 发送请求
				try {
				  const result = await postProgramCustomerIntention([{
					 operationType:"CREATE", // 操作类型
					 customerCode:customerCode, // 客户编码
					 userID:userID, // 用户唯一标识
					 businessType:businessCode, // 业务类型编码
					 cusEntryName: that.CusEntryName, // 客户名称
					 sampleType: that.SampleType, // 样品类型
					 contactMan: that.ContactMan, // 联系人
					 phone: that.Phone, // 电话
					 sampleInfo: that.SampleInfo,  // 样品信息
					 emailCode: that.EmailCode,  // 邮寄单号
					 remark:that.Remark, // 备注
					 attach:that.Attachment, // 附件
				  }]);
				  if (result.code == 200) {
				    // console.log("在线预约成功！！！",result);
					that.$refs.bookingModal.close();
					if(!userPhone){
						return this.$toast({
						  title: "预约成功",
						  icon: "success",
						});
					}
					this.$toast({
					  title: "预约成功",
					  icon: "success",
					  success:() => {
						  var nav = setTimeout(()=>{
						  	that.getProgramCustomerIntentionData();
						  	clearTimeout(nav)
						  },500)
					  }
					});
					
				  } else {
				    return this.$toast({
				      title: result.data.msg,
				    });
				  }
				} catch (error) {
				  console.error("请求失败", error);
				  return this.$toast({
				    title: "请求失败",
				    icon: "error",
				  });
				}
			},
			// 意向单查询
			async getProgramCustomerIntentionData(contactMan){
				const { userPhone } = uni.getStorageSync("userInfo");
				if(!userPhone){
					// return this.$toast({
					//   title: "请先登录授权！",
					//   icon: "error",
					// });
					return false;
				}
				// 发送请求
				try {
				  const result = await getProgramCustomerIntention([{
					 phone: userPhone,
					 contactMan:contactMan
				  }]);
				  if (result.code == 200) {
					  this.bookingList = result.data;
				      // console.log("意向单查询成功！！！",result);
				  } else {
				    this.$toast({
				      title: result.data.msg,
				    });
				    return false;
				  }
				} catch (error) {
				  console.error("请求失败", error);
				  this.$toast({
				    title: "请求失败",
				    icon: "error",
				  });
				  return false;
				}
			},
			// 添加意向单
			onAddBooking(){
				this.$refs.bookingModal.open();
			},
			onBookingClose(){
				this.$refs.bookingModal.close();
			},
			// 删除附件
			onDelFiles(index) {
				this.Attachment.splice(index, 1)
			},
			// 上传文件
			onUploadFile() {
				let that = this;
				// 选择文件 chooseFile:H5   chooseMessageFile:小程序  APP图片和视频chooseMedia
				uni.chooseImage({
					count: 1,  // 最多可以选择的图片张数
					sizeType: ['original', 'compressed'],  // 可以选择原图或压缩图
					sourceType: ['album', 'camera'],  // 'album' 从相册选择, 'camera' 使用相机拍照
					success: function(res) {
						// console.log("选择文件", res)
						// 获取选择的文件的临时文件路径
						// var tempFilePath = res.tempFiles[0].path;
						var tempFilePath = res.tempFilePaths[0];
						// 使用 split() 方法来分割路径
						that.fileName = tempFilePath.split('/').pop();
						
						// 获取文件name
						// var name = res.tempFiles[0].name;
						uni.showLoading({
							title: '正在上传文件...'
						})
						
						// 使用 canvas 压缩图片
					// 	that.compressImageToBase64(tempFilePath).then((base64) => {
					// 	  uni.hideLoading();
						  
					// 	  // 转换后的 base64 图片
					// 	  // console.log('压缩后的 base64:', base64);
					
					// 	  // 修正 base64 格式
					// 	  const fixedBase64 = that.validateAndFixBase64(base64);
					
					// 	  // 上传文件
					// 	  that.Attachment.push({
					// 		attName: that.fileName,
					// 		attValue: fixedBase64
					// 	  });
					// 	}).catch((err) => {
					// 	  uni.hideLoading();
					// 	  // console.log("压缩转base64错误", err);
					// 	});
						
						wx.compressImage({
						      src: tempFilePath,
						      quality: 80,  // 压缩质量，0-100之间，值越小，图片越小
						      success(compressedRes) {
						        const compressedFilePath = compressedRes.tempFilePath;
						        console.log('压缩后的图片路径:', compressedFilePath);
						        // 接下来可以将压缩后的图片上传或转换为base64
								// that.ploadFilePromise(tempFilePath)
								pathToBase64(compressedFilePath).then(res => {
									uni.hideLoading();
									//res为图片路径
									// console.log("转base64后的路径",res)
									const base64 = res.substr(22);
									const fixedBase64 = that.validateAndFixBase64(base64);
									// console.log("正则后的base64",fixedBase64)
									that.Attachment.push({
										attName: that.fileName,
										attValue: fixedBase64
									})
									// this.previewFiles.push(res)
								}).catch((err)=>{
									uni.hideLoading();
									console.log("压缩转base64错误",err)
								})
						      }
						});
					},
					fail: function(err) {
						console.error('选择文件失败:', err);
					}
				});
			},
			// 使用 Canvas 进行图片压缩并转换为 Base64
			// compressImageToBase64(imagePath) {
			//   return new Promise((resolve, reject) => {
			//     const img = new Image();
			//     img.src = imagePath;
			
			//     img.onload = function () {
			//       const canvas = document.createElement('canvas');
			//       const ctx = canvas.getContext('2d');
			//       const MAX_WIDTH = 800; // 设置最大宽度
			//       const MAX_HEIGHT = 800; // 设置最大高度
			
			//       let width = img.width;
			//       let height = img.height;
			
			//       // 根据图片比例缩放图片
			//       if (width > height) {
			//         if (width > MAX_WIDTH) {
			//           height = Math.round(height * MAX_WIDTH / width);
			//           width = MAX_WIDTH;
			//         }
			//       } else {
			//         if (height > MAX_HEIGHT) {
			//           width = Math.round(width * MAX_HEIGHT / height);
			//           height = MAX_HEIGHT;
			//         }
			//       }
			
			//       canvas.width = width;
			//       canvas.height = height;
			//       ctx.drawImage(img, 0, 0, width, height);
			
			//       // 将压缩后的图片转成 Base64 格式
			//       const base64 = canvas.toDataURL('image/jpeg', 0.8); // 0.8 为压缩质量，取值范围 0 - 1
			//       resolve(base64);
			//     };
			
			//     img.onerror = function () {
			//       reject('图片加载失败');
			//     };
			//   });
			// },
			validateAndFixBase64(input) {
			    // 移除所有非Base-64字符（例如空格和换行符）
			    input = input.replace(/[^A-Za-z0-9+/=]/g, '');
			
			    // 检查并修复填充字符
			    const padding = input.length % 4;
			    if (padding === 2) {
			        input += '==';  // 添加两个填充字符
			    } else if (padding === 3) {
			        input += '=';   // 添加一个填充字符
			    }
			
			    // 检查是否修正后仍为有效的Base-64字符串
			    const regex = /^[A-Za-z0-9+/=]+$/;
			    if (!regex.test(input)) {
			        throw new Error('Invalid Base64 string');
			    }
			    return input;
			}
		}
	}
</script>

<style lang="scss">
	// page{
	// 	background-color: rgb(249,250,251);
	// 	// height: 100vh;
	// }
	/* app端 */
	/* #ifdef APP-PLUS || H5 */
	#app,
	/* #endif */
	page {
	  background-color: #F9FAFB;
	  height: 100%;
	}
	.disw{
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
	.booking{
		display: flex;
		flex-direction: column;
		height: 100vh;
		// background-color: rgb(249,250,251);
		.mybook{
			// margin: 20rpx;
			flex: 1;
			width: auto;
			overflow-y: auto;
			.bkitem{
				padding: 0 20rpx 20rpx;
				font-size: 25rpx;
				margin: 20rpx;
				background-color: #fff;
				box-shadow: #bbb 0 0 8rpx;
			    border-radius: 15rpx;
				// box-shadow: 0 0 15rpx rgba(0, 0, 0, 0.1);
				// border-bottom: 1rpx solid #f4f4f4;
				.bkdjs{
					display: flex;
					align-items: center;
					justify-content: space-between;
					.controls{
						color: #0081ff;
						.rolsl{
							margin-right: 10rpx;
						}
					}
				}
				.pd10{
					padding: 10rpx 0;
				}
				.bkrol{
					// height: 60rpx;
					// line-height: 60rpx;
					padding: 10rpx 0;
					.sheetc{
						font-size: 30rpx;
						font-weight: bold;
					}
				}
				.remark{
					margin: 10rpx 0rpx;
				}
			}
		}
	}
	.colors{
		color: #6C7381;
	}
	.colorb{
		color: #000;
	}
	.names{
		font-size: 28rpx;
		font-weight: bold;
	}
	.status{
		color: #FFF;
		background: #FF0000;
		padding: 5rpx 10rpx;
		border-radius: 10rpx;
	}
	.uni-dialog-content{
		padding: 40rpx 20rpx !important;
	}
	.uni-dialog-title{
		padding-top: 10px !important;
	}
	.uni-collapse-item__title-wrap > .uni-collapse-item__title-box{
		height: unset !important;
		min-height: 60rpx !important;
		line-height: 60rpx !important;
		padding: 0rpx !important;
	}
	.uni-collapse-item__title-text{
		font-size: 25rpx !important;
	}
	.form-item::after {
	  content: "";
	  display: block;
	  clear: both;
	}
	.form-wrap {
		background: #fff;
		border-radius: 30rpx;
		padding: 20rpx 45rpx;
		box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.1);
	
		&.modal {
			box-shadow: none;
			padding: 0;
			flex: 1;
	
			.form-item {
				&:first-child {
					padding-top: 0;
				}
	
				&:last-child {
					padding-bottom: 0;
				}
			}
		}
		
		.form-item {
			display: block;
			font-size: 28rpx;
			border-bottom: 1px solid #f2f2f2;
			padding: 12rpx 0;
			&:first-child {
				border-bottom: 1px solid #f2f2f2 !important;
			}
			&:last-child {
				border-bottom: 0;
			}
		}
	}
	
	// 吸底工具栏
	.toolbars {
		position: fixed;
		left: 0;
		right: 0;
		bottom: var(--window-bottom);
		z-index: 1;
		height: 100rpx;
		display: flex;
		padding: 0 15rpx;
		align-items: center;
		border-top: 1rpx solid #ededed;
		border-bottom: 1rpx solid #ededed;
		background-color: #fff;
		box-sizing: content-box;
	
		.button-grounp {
			margin-left: auto;
			display: flex;
			justify-content: space-between;
			text-align: center;
			line-height: 72rpx;
			font-size: 13px;
			color: #fff;
	
			.button {
				width: 200rpx;
				margin: 0 10rpx;
				border-radius: 72rpx;
			}
	
			.payment-button {
				// background-color: #6887e1;
				background-color: #007AFF;
				.icons{
					// border: 1rpx solid #fff;
					// border-radius: 50%;
					// padding: 7rpx;
					margin-right: 10rpx;
				}
			}
		}
	}
	.uploadfile {
		width: 130rpx;
		height: 55rpx;
		line-height: 55rpx;
		border-radius: 15rpx;
		background: #007AFF;
		text-align: center;
		color: #fff;
		padding: 0 10rpx;
		margin: 20rpx 0rpx;
		font-size: 25rpx;
		float: right;
	}
	
	.filelist {
		// border-bottom: 1rpx solid #e1e1e1;
		max-height: 200rpx;
		overflow-y: auto;
		font-size: 25rpx;
		margin-bottom: 50rpx;
		float: left;
		max-width: 280px;
		.files {
			padding: 15rpx 15rpx;
			border-radius: 15rpx;
			margin-bottom: 5rpx;
			margin-top: 5rpx;
			border: solid 1rpx rgb(238, 238, 238);
			display: flex;
			justify-content: space-between;
			.textf{
				text-overflow: ellipsis;
				overflow: hidden;
				white-space: nowrap;
				margin-right: 50rpx;
			}
			.delfiles {
				position: relative;
				&:before,
				&:after {
					content: '';
					position: absolute;
					top: 50%;
					right: 0;
					width: 30rpx;
					height: 1rpx;
					background-color: #333;
					/* 交叉线的颜色 */
					transform-origin: center;
					transform: translateX(-50%);
				}
	
				&:before {
					transform: translateX(-50%) rotate(45deg);
					/* 第一条线旋转45度 */
				}
	
				&:after {
					transform: translateX(-50%) rotate(-45deg);
					/* 第二条线旋转-45度 */
				}
			}
		}
	}
	// 底部占位空盒子
	.toolbar-height {
		height: 100rpx;
	}
	// .uni-scroll-view, .uni-scroll-view-content{
	// 	overflow: unset !important; 
	// }
</style>